package com.example.init.controller.HTTPController;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

@RestController
@RequestMapping("/session")
public class SessionController {

    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request){
        HttpSession session = request.getSession(true);
        session.setAttribute("username","wen");//设置 session
        return "set success";
    }

    @RequestMapping("/session1")
    public String  getSession(HttpServletRequest request){
        HttpSession session = request.getSession(false);//设置为 false session 为空不创建 HttpSession 对象
        if(session != null){
            String sessionValue = (String) session.getAttribute("username");
            return "登录用户"+sessionValue;
        }
        return "session 为空";
    }

    /**
     * 使用 注解方式 获取Session 默认是必填参数,设置 required 为 false -> 参数为 非必填
     * @param username
     * @return
     */
    @RequestMapping("/session2")
    public String getSession2(@SessionAttribute(required = false) String username){
        return "username:"+username;
    }

    @RequestMapping("/session3")
    public String getSession3(HttpSession session){
        String username = (String) session.getAttribute("username");
        return "登录用户:" + username;
    }

}
